var GrdLayUI = {
    layer: null,//layer 弹框控件
    laydate: null,//日历控件
    laytable: null,//表格控件
    form: null,//表单
    init: function () {
        GrdLayUI.layer = window.top.layui.layer;
        GrdLayUI.laydate = layui.laydate;
        GrdLayUI.laytable = layui.table;
        GrdLayUI.form = layui.form;

    },
    /*
    * jQuery        Ajax调用封装
    * url:			调用地址
    * data:			可选参数,表示Ajax调用参数
    * onSuccess:	可选参数,成功回调函数,函数签名为  function(data), data参数为调用结果
    * onError:		可选参数,失败回调函数,函数签名为  function (XMLHttpRequest, textStatus, errorThrown)
    * modal:		可选参数,是否作为模态对话框显示，默认为true
    * datatype:		可选参数,Ajax返回数据类型,默认为 "json"
    * cache:		可选参数,Ajax调用是否启用缓存,默认为 false
    * onComplete:	可选参数,Ajax调用完成回调函数,函数签名为  function (XMLHttpRequest, textStatus)
    * async:		可选参数,是否异步调用，默认为true
    */
    ajaxPost: function (param) {
        param.modal = (param.modal === false ? false : true);
        if (param.modal) {
            this.loading.start();
        }
        var ajaxHandler =
            $.ajax({
                url: param.url,
                data: { param: GrdLayUI.zip(param.data) },
                //data: JSON.stringify(param.data),
                type: "POST",
                dataType: param.datatype ? param.datatype : "json",
                //contentType:"application/json;charset=utf-8",   
                contentType: "application/x-www-form-urlencoded",
                cache: param.cache ? param.cache : false,
                async: (param.async == null || param.async == undefined) ? true : param.async,
                success: function (json) {
                    if (param.modal) {
                        GrdLayUI.loading.end();
                    }
                    var result = json || null;
                    try {
                        result.Data = JSON.parse(result.Data || null);
                    } catch (e) {

                    }
                    param.success(result);
                    if (!result.Success) {
                        //信息框
                        GrdLayUI.layer.alert(result.Msg, "警告");
                    }
                },
                //统一的错误信息处理
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                    var error = (XMLHttpRequest && XMLHttpRequest.responseText) || '未知错误';
                    if (param.onError) {
                        param.onError(XMLHttpRequest, textStatus, errorThrown, error);
                    }
                    //信息框
                    GrdLayUI.layer.alert(error, "错误");
                    GrdLayUI.loading.end();
                },
                complete: function (XMLHttpRequest, status) {

                    //请求完成后最终执行参数
                    if (status == 'timeout') {
                        //超时,status还有success,error等值的情况
                        GrdLayUI.layer.alert("访问超时!", "警告");
                        this.ajaxHandler.abort();
                        GrdLayUI.loading.end();
                    }
                },
                statusCode: {
                    500: function () {
                        GrdLayUI.layer.alert("系统500错误!", "错误!");
                    }
                }
            });
    },

    /**
     * 研所参数
     * @param {any} jsonObj
     */
    zip: function (jsonObj) {
        if (!jsonObj) return jsonObj;
        if (jsonObj instanceof String) {
            return encodeURIComponent(jsonObj);
        } else {
            return encodeURIComponent(JSON.stringify(jsonObj));
        }
    },
    //消息框
    alert: function (content, type, title) {
        if (type === "警告")
            return GrdLayUI.layer.alert(content, { icon: 0, offset: "auto", title: title || "警告" });
        else if (type === "成功")
            return GrdLayUI.layer.alert(content, { icon: 1, offset: "auto", title: title || "成功" });
        else if (type === "错误")
            return GrdLayUI.layer.alert(content, { icon: 2, offset: "auto", title: title || "错误" });
        else
            return GrdLayUI.layer.alert(content, { offset: "auto", title: title || "提醒" });
    },
    //提示框
    msg: function (content, type, func, time) {
        if (type === "警告")
            return GrdLayUI.layer.msg(content, { icon: 0, offset: "auto", time: time || 4 * 1000 }, func);
        else if (type === "成功")
            return GrdLayUI.layer.msg(content, { icon: 1, offset: "auto", time: time || 2 * 1000 }, func);
        else if (type === "错误")
            return GrdLayUI.layer.msg(content, { icon: 2, offset: "auto", time: time || 4 * 1000 }, func);
        else
            return GrdLayUI.layer.msg(content, { offset: "auto", time: time || 2 * 1000 }, func);
    },
    //询问框
    confirm: function (content, yes, cancel, title) {
        GrdLayUI.layer.confirm(content, { icon: 3, offset: "auto", title: title || "提醒" }, yes, cancel);
    },
    //加载
    loading: {
        index: 0,
        start: function () {
            this.index = GrdLayUI.layer.load(1, { shade: [0.1, "#fff"], time: 600 * 60 * 1000 });
        },
        end: function () {
            var _this = this;
            GrdLayUI.layer.close(_this.index);
        }
    },
    /**
     * 根据Iframe的name 获取Ifram对象 dx对象可不用传递
     * @param {any} name
     * @param {any} dx
     */
    getIframeObj: function (name, dx) {
        var f;
        if (dx == "" || dx == null || dx == undefined) {
            dx = "top"; f = eval(dx + ".frames");
        }
        else {
            f = eval(dx);
        }
        for (var i = 0; i < f.length; i++) {
            if (f[i].length > 0) {
                return GrdLayUI.getIframeObj(name, dx + ".frames['" + f[i].name + "']");
            }
            else {
                if (f[i].name == name) {
                    return dx + ".frames['" + name + "']";
                }
            }
        }
    },
    /**
     * 执行某个Iframe中的函数 funName：函数名（参数1，参数2，...）  iframeName：iframe名字
     * @param {any} funName
     * @param {any} iframeName
     */
    exFunction: function (funName, iframeName) {
        try {
            eval(GrdLayUI.getIframeObj(iframeName) + "." + funName + ";");
            return true;
        } catch (e) {
            throw new Error(e.message);
            return false;
        }
    },
    getParentFrameName: function () {
        return top.$("#" + GrdLayUI.getIframeName()).attr("data-parentiframename");
    },
    /**
     * 获取layeriframe窗口的index
     */
    getLayerIframeIndex: function () {
        return GrdLayUI.layer.getFrameIndex(window.name);
    },
    getIframeName: function () {
        return "layui-layer-iframe" + GrdLayUI.getLayerIframeIndex();
    },
    /*
     * 查找带回
     */
    findBack: {
        close: function (row) {
            var findback = GrdLayUI.getQueryString("findback");
            if (findback) {
                GrdLayUI.setSession('findBackJson', row);
                GrdLayUI.layer.close(GrdLayUI.getLayerIframeIndex());
            }
        },
        open: function (content, title, callBack, w, h, isFull, parentIframeName) {
            GrdLayUI.openWindow({
                content: content,
                title: title || "查找带回",
                IsFull: isFull,
                width: w ? w : "1200px",
                height: h ? h : "1200px",
                btn: false,
                success: function (layero) {
                    $(layero).find("iframe").attr("data-parentiframename", parentIframeName || GrdLayUI.getIframeName());
                },
                end: function () {
                    var findBackJson = GrdLayUI.getSession("findBackJson");
                    if (callBack && findBackJson && findBackJson.length > 0) {
                        callBack(findBackJson);
                    }
                    GrdLayUI.setSession("findBackJson", []);
                }
            });
        }
    },
    /**
     * 将图片对象转换为 base64
     * @param {any} obj
     * @param {any} callBack
     */
    readFile: function (obj, callBack) {
        var file = obj.files[0];
        var resVal;
        //判断类型是不是图片  
        if (!/image\/\w+/.test(file.type)) {
            alert("请确保文件为图像类型");
            return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) {
            //alert(this.result); //就是base64  
            resVal = this.result;
            if (callBack) callBack(resVal);
            //return resVal;
        }

    },
    setSession: function (key, value) {
        window.top.localStorage.setItem(key, JSON.stringify(value));
    },
    getSession: function (key) {
        return JSON.parse(window.top.localStorage.getItem(key));
    },

    /* @url：远程地址
     * @param：url 远程地址
     * @param：selectorStr 内部创建的iframe置放于哪个位置，选择器字符串
     * @summary：使用js下载文件，可有提示操作
     */
    exportFile: function (url, selectorStr) {
        var selector = selectorStr || "body";
        $("<iframe/>", { id: "exportIframe", src: url, width: 0, height: 0 }).appendTo(selector);
        setTimeout(function () {
            $("#exportIframe").remove();
        }, 2000);
    },
    /**
     * Form清空
     */
    clearForm: function (FormId) {
        $("#" + FormId).find("input,textarea,select").each(function () {
            var type = $(this)[0].tagName.toLowerCase();
            var classText = $(this).attr("class");
            switch (type) {
                case "input":
                case "textarea":
                    $(this).val("");
                    if (classText != undefined && classText.indexOf("easyui") > -1) {
                        $(this).textbox('setValue', "");
                    }
                    break;
                case "select":
                    $(this).val("");
                    if (classText != undefined && classText.indexOf("easyui") > -1) {
                        $(this).textbox('setValue', "");
                    }
                    break;
                default:
            }
        });
    },
    /**
     * Form清空,ids中的保留
     */
    clearFormByCondition: function (FormId, ids) {
        $("#" + FormId).find("input,textarea,select").each(function () {
            var type = $(this)[0].tagName.toLowerCase();
            var classText = $(this).attr("class");
            var id = $(this).attr("id");

            if ($.inArray(id, ids) < 0) {
                switch (type) {
                    case "input":
                    case "textarea":
                        $(this).val("");
                        if (classText.indexOf("easyui") > -1) {
                            $(this).textbox('setValue', "");
                        }
                        break;
                    case "select":
                        $(this).val("");
                        if (classText.indexOf("easyui") > -1) {
                            $(this).textbox('setValue', "");
                        }
                        break;
                    default:
                }
            }
        });
    },

    /*
     * @pNode:from或table大界定范围
     * @param:pNodes dom对象
     * @summary:自动拉取pNode子集input/textarea、img值生成model
    */
    initParamsData: function (pNodes) {
        var params = {};
        for (var i = 0; i < pNodes.length; i++) {
            var saveNode = pNodes[i];
            ($("input:not(input:file,input:radio,input:checkbox),textarea", saveNode).not("[except]")).each(function () {
                params[(this.name || this.id)] = $(this).val().trim();
            });
            ($("input:radio:checked", saveNode).not("[except]")).each(function () {
                params[this.getAttribute("name")] = ($(this).val() || 0);
            });
            ($("input:checkbox", saveNode).not("[except]")).each(function () {
                params[(this.name || this.id)] = $(this).prop("checked");
            });
            ($("input:hidden[savedata]", saveNode).not("[except]")).each(function () {
                params[this.name] = $(this).val().trim();
            });
            ($("select", saveNode).not("[except]")).each(function () {
                params[(this.name || this.id)] = $(this).val();
                $(this).attr("isText") && (params[this.name] = $(this).find("option:selected").text());
            });
            ($("img", pNodes).not("[except]")).each(function () {
                params[(this.name || this.id)] = ($(this).attr('data-savesrc') || $(this).attr('src'));
            })
        }
        return params;
    },
    /**
     * 赋值
     * @param {any} pNodes
     *  @param {string} jsonStr
     */
    assignmentData: function (pNodes, jsonObj) {
        var jsonData = null;
        if (typeof jsonObj == "string") {
            jsonData = JSON.parse(decodeURIComponent(jsonObj));
        } else {
            jsonData = jsonObj;
        }
        for (var i = 0; i < pNodes.length; i++) {
            var node = pNodes[i];
            $('input:not(input:file,input:radio,input:checkbox),textarea').each(function () {
                
                //console.log("input:not(input:file,input:radio,input:checkbox),textarea ---" + this.name);
                //debugger

                var eValue = eval('jsonData.' + this.name);
                if (eValue) {
                    $(this).val(eValue);
                }
            });

            $("input[type='radio']").each(function () {

                //console.log("radio ---" + this.name);
                //debugger

                var eValue = eval('jsonData.' + this.getAttribute("name"));
                $("input[name='" + this.getAttribute("name") + "'][value=" + eValue + "]").attr("checked", true);
            });


            $("input:checkbox").each(function () {

                //console.log("checkbox ---" + this.name);
                 //debugger

                var eValue = eval('jsonData.' + this.name);
                if (eValue) {
                    $(this).attr("checked", "checked");
                    //$(this).prop("checked") = eValue;
                }
            });

            $("input:hidden[savedata]").each(function () {

                //console.log("savedata ---" + this.name);
                //debugger

                var eValue = eval('jsonData.' + this.name);
                if (eValue) {
                    $(this).val(eValue);
                }
            });

            $("select").each(function () {

                //console.log("select ---" + this.name);
                //debugger

                var eValue = eval('jsonData.' + this.name);
                if (eValue) {
                    $(this).val(eValue);
                }
            });

            $("img").each(function () {

                //console.log("img ---" + this.name);
                //debugger

                var eValue = eval('jsonData.' + this.name);
                if (eValue) {
                    $(this).attr('src') = eValue;
                    $(this).attr('data-savesrc') = eValue;
                }
            })
        }
    },

    /**
     * 将传输参数转换成json
     * @param {any} jsonObj
     */
    toJsonData: function (jsonObj) {
        var jsonData = null;
        if (typeof jsonObj == "string") {
            jsonData = JSON.parse(decodeURIComponent(jsonObj));
        } else {
            jsonData = jsonObj;
        }
        return jsonData;
    },

    /**
     * 表单赋值
     * @param {any} formId
     * @param {any} jsonObj
     */
    assignmentFormData: function (formId, jsonObj) {
        var jsonData = null;
        if (typeof jsonObj == "string") {
            jsonData = JSON.parse(decodeURIComponent(jsonObj));
        } else {
            jsonData = jsonObj;
        }
        GrdLayUI.form.val(formId, jsonData);
    },

    /**
     * 初始化table
     * @param {any} param
     * param.dom  容器
     * param.url 请求地址
     * param.title cols
     */
    table: function (param) {
        //列表
        GrdLayUI.laytable.render({
            elem: param.dom,
            cellMinWidth: 100,
            method: 'post',
            url: param.url,
            where: {
                field: param.field,
                order: param.order,
                parameters: GrdLayUI.zip(param.parameters)
            },
            page: true,
            sort: true, //重点1：这里的sort表示 table表在取得接口数据后，对页面渲染后的table数据进行排序。同时，这里的true 会影响页面sort 上下小箭头的 显示效果
            height: param.height != undefined ?param.height:"full-110",
            limits: [15, 30, 45, 60],
            limit: 15,
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": res.Msg, //解析提示文本
                    "count": res.Count, //解析数据长度
                    "data": res.Data //解析数据列表
                };
            },
            //done: function (res, curr, count) {
            //    this.where = {};
            //},
            cols: [param.title]
            //,
            //jump: function (obj, first) {
            //    //obj包含了当前分页的所有参数，比如：
            //    console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
            //    console.log(obj.limit); //得到每页显示的条数
            //    //首次不执行
            //    if (!first) {
            //        //do something
            //    }
            //}
        });
    },
    /**
     * table重载
     * */
    tableReload: function (param) {
        GrdLayUI.laytable.reload(
            param.domId,
            {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    field: param.field,
                    order: param.order,
                    parameters: GrdLayUI.zip(param.parameters)
                }
            });
    },
    /**
     * table //排序监听
     */
    tableSort: function (param) {

        GrdLayUI.laytable.on('sort(' + param.domId + ')',
            function (obj) {
                param.backAction(obj);
                //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                //obj.field 当前排序的字段名
                //obj.type 当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
                //self.Parameters.field = obj.field;
                //self.Parameters.order = obj.type;
                //self.logicFunc.loadListInfo();
            });
    },
    /**
     * 获取选中数据
     */
    getCheckData: function (param) {
        var checkStatus = GrdLayUI.laytable.checkStatus(param.domId);
        var data = checkStatus.data;
        if (data.length <= 0) {
            GrdLayUI.msg("请选择需操作行数据", "警告");
            return;
        }
        if (param.backAction) {
            param.backAction(data);
        } else {
            return data;
        }
    },

    //获取单选数据
    getSingleCheckData: function (param) {
        var checkStatus = GrdLayUI.laytable.checkStatus(param.domId);
        var data = checkStatus.data;
        if (data.length <= 0) {
            GrdLayUI.msg("请选择需操作行数据", "警告");
            return;
        }
        if (data.length > 1) {
            GrdLayUI.msg("请选择一行需操作行数据", "警告");
            return;
        }
        if (param.backAction) {
            param.backAction(data[0]);
        } else {
            return data;
        }
    },

    //删除信息
    removeDataById: function (param) {
        var checkStatus = GrdLayUI.laytable.checkStatus(param.domId);
        var data = checkStatus.data;
        if (data.length <= 0) {
            GrdLayUI.msg("请选择需操作行数据", "警告");
            return;
        }
        GrdLayUI.confirm("确定删除信息吗？", function () {
            var arrayObj = new Array();　//创建一个数组
            $.each(data, function (n, value) {
                arrayObj.push(value.ID);
            });
            var json = {
                parameters: arrayObj
            };
            GrdLayUI.ajaxPost({
                url: param.removeUrl,
                data: json,
                success: function (result) {
                    if (result.Code == 1000) {
                        GrdLayUI.msg(result.Msg, "成功", function () {
                            if (param.backAction) {
                                param.backAction(result);
                            } else {
                                return data;
                            }
                        });
                    } else {
                        GrdLayUI.msg(result.Msg, "警告");
                    }
                }
            });
        });
    },

    //删除信息
    removeData: function (param) {
        var checkStatus = GrdLayUI.laytable.checkStatus(param.domId);
        var data = checkStatus.data;
        if (data.length <= 0) {
            GrdLayUI.msg("请选择需操作行数据", "警告");
            return;
        }
        GrdLayUI.confirm("确定删除信息吗？", function () {
            var arrayObj = new Array();　//创建一个数组
            $.each(data, function (n, value) {
                arrayObj.push(value.gCode);
            });
            var json = {
                parameters: arrayObj
            };
            GrdLayUI.ajaxPost({
                url: param.removeUrl,
                data: json,
                success: function (result) {
                    if (result.Code == 1000) {
                        GrdLayUI.msg(result.Msg, "成功", function () {
                            if (param.backAction) {
                                param.backAction(result);
                            } else {
                                return data;
                            }
                        });
                    } else {
                        GrdLayUI.msg(result.Msg, "警告");
                    }
                }
            });
        });
    },

    //根据传入信息删除信息
    removeDataByIdInfo: function (param) {
        var paramData = param.data;
        if (paramData.length <= 0) {
            GrdLayUI.msg("请选择需操作行数据", "警告");
            return;
        }
        GrdLayUI.confirm("确定删除信息吗？", function () {
            //判断是否为数组  返回Boolean
            var bool = $.isArray(paramData);
            var json = null;
            //创建一个数组
            var arrayObj = new Array();
            if (bool) {
                $.each(paramData, function (n, value) {
                    arrayObj.push(value.ID);
                });
            } else {
                arrayObj.push(paramData.ID);
            }
            json = {
                parameters: arrayObj
            };
            GrdLayUI.ajaxPost({
                url: param.removeUrl,
                data: json,
                success: function (result) {
                    if (result.Code == 1000) {
                        GrdLayUI.msg(result.Msg, "成功", function () {
                            if (param.backAction) {
                                param.backAction(result);
                            } else {
                                return data;
                            }
                        });
                    } else {
                        GrdLayUI.msg(result.Msg, "警告");
                    }
                }
            });
        });
    },

    //根据传入信息删除信息
    removeDataByInfo: function (param) {
        var paramData = param.data;
        if (paramData.length <= 0) {
            GrdLayUI.msg("请选择需操作行数据", "警告");
            return;
        }
        GrdLayUI.confirm("确定删除信息吗？", function () {
            //判断是否为数组  返回Boolean
            var bool = $.isArray(paramData);
            var json = null;
            //创建一个数组
            var arrayObj = new Array();
            if (bool) {
                $.each(paramData, function (n, value) { 
                    arrayObj.push(value.gCode);
                });
            } else {
                arrayObj.push(paramData.gCode);
            }
            json = {
                parameters: arrayObj
            };
            GrdLayUI.ajaxPost({
                url: param.removeUrl,
                data: json,
                success: function (result) {
                    if (result.Code == 1000) {
                        GrdLayUI.msg(result.Msg, "成功", function () {
                            if (param.backAction) {
                                param.backAction(result);
                            } else {
                                return data;
                            }
                        });
                    } else {
                        GrdLayUI.msg(result.Msg, "警告");
                    }
                }
            });
        });
    }

};

//GrdLayUI 框架初始化
GrdLayUI.init();